package com.cndw.kungfu.model.goods.app;

import java.util.HashMap;
import java.util.Map;

import com.cndw.kungfu.domain.GoodsMode;
import com.cndw.kungfu.exception.ErrObjectException;
import com.cndw.kungfu.exception.ErrPopException;
import com.cndw.kungfu.ext.LangUtil;
import com.cndw.kungfu.ext.LanguageLib;
import com.cndw.kungfu.ext.LogUtil;
import com.cndw.kungfu.ext.NumberProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.activity.domain.KeyChest;
import com.cndw.kungfu.model.sys.ChatMain;

/**
 * 开启宝箱
 * 
 * @author fantadust [9677889@qq.com]
 * @date 2012-1-11 下午5:56:57
 */
public class AppDo108 extends AppBase {

	private StringBuffer sb = new StringBuffer();
	String keyName = null;

	@Override
	public boolean check() throws Exception {
		KeyChest keyChest = KeyChest.getKeyChest(goodsId);
		if (keyChest == null) {
			throw new ErrPopException(LanguageLib.get("comm.err.args"));
		}
		if (keyChest.getKeyId() > 0) {
			GoodsMode keyMode = Context.getGoodsServer().getModeById(keyChest.getKeyId());
			if (!player.getPlayerBoxs().isHaveGoods(keyChest.getKeyId())) {
				Map<String, Object> obj = new HashMap<String, Object>();
				obj.put("keyId", keyChest.getKeyId());
				obj.put("_appId", goodsMode.getAppId());
				throw new ErrObjectException(obj);
			}
			keyName = keyMode.getName();
			player.getPlayerBoxs().costGoods(keyChest.getKeyId(), 1);
			sb.append(LanguageLib.get("goods.use.costgoods", keyMode.getName()));
			
		}
		return true;
	}

	@Override
	public Map<String, Object> run() throws Exception {
		KeyChest keyChest = KeyChest.getKeyChest(goodsId);
		int currentRate = NumberProcesser.mtRand(10000);
		int tmpRate = 0;
		int finalIndex = 0;
		for (int i = 0; i < keyChest.getRates().length; i++) {
			tmpRate += keyChest.getRates()[i];
			if (currentRate <= tmpRate) {
				finalIndex = i;
				break;
			}
		}
		String awardName = null;
		if (finalIndex >= 0 && keyChest.getAwards().length > finalIndex) {
			int finalGoodsId = keyChest.getAwards()[finalIndex];
			GoodsMode awardMode = Context.getGoodsServer().getModeById(finalGoodsId);
			if (awardMode != null) {
				Context.getGoodsServer().giveGoods(playerId, finalGoodsId, 1);
				awardName = awardMode.getName();
				sb.append(LanguageLib.get("goods.use.getgoods", awardMode.getName()));

				//String message = LanguageLib.get("board.chest.use", player.getPlayerName(), goodsMode.getName(), awardName,
				//		LangUtil.getColor(awardMode.getColor()));
				String message = LanguageLib.get("board.chest.use", LangUtil.makeNameLink(player), goodsMode.getName(), awardName,
						LangUtil.getColor(awardMode.getColor()));
				ChatMain.systemMessage(message);
			}
		} else {
			LogUtil.getMain().error("err " + finalIndex);
			return msg;
		}

		logString = sb.toString();
		ticpString = LanguageLib.get("goods.use.keysuc", awardName, keyName);
		return msg;
	}
}
